<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//借支
class Jiezhi extends CommonController {

	function __construct(){
		
		parent::__construct();
		$this->load->model('Chuna/cashiersModel','CurModel');
		
		$this->load->model('Chuna/CashBalanceModel','CashBalanceModel');
		
	}
	
	
	//start
	/**
	* @name 获取列表
	* @param page ture char 页面
	* @param size ture char 数量
	* @return 成功返回1
	*/
	//end
	function get_list(){
		$user_id = $this->user_id;
		
		
		if(!$this->check_priv('chuna_jiezhi|chuna_jiezhi_1')){
			$this->err_out(LANG_NOPRIV);
		}


		$page = $this->input->post('page',null,1);
		$size = $this->input->post('size',null,10);
		
		$filter = $this->input->post('f',null,array());

		
		if(empty($filter['date_month'])){
			//$this->err_out('请选择月份');
		}
		else{
			$filter['date_month'] = date('Y-m',strtotime($filter['date_month'].'-01'));
		}
		// if(!empty($filter['date_month'])){
		// 	$filter['date_month'] = date('Y-m',strtotime($filter['date_month'].'-01'));
		// }
		
		$filter['subject'] = '1031借支';

		$arr = $filter;
		
		$res = $this->CurModel->get_jiezhi_list($arr,$page,$size);
		$list = $res['list'];
		
		$ls_arr = $filter;
		$ls_arr['mtype'] = 1;
		$total = $this->CurModel->get_totals($ls_arr,'expenses');
		
		$ls_arr = $filter;
		$ls_arr['mtype'] = 0;
		$total_huai = $this->CurModel->get_totals($ls_arr,'income');
		
		$total_yu = $total - $total_huai;
		$this->load->model('User/UserModel','UserModel');
		
		foreach($list as $key=>$val){
			$list[$key]['month'] = date('m',strtotime($val['date']));
			$list[$key]['day'] = date('d',strtotime($val['date']));
			
			$list[$key]['huai_date'] = !empty($val['addtime'])?date('Y-m-d',$val['addtime']):'';
			
			//获取已经还了钱的总数
			$num = 0;
			$num = $this->CurModel->get_totals(array('pid'=>$list[$key]['id']),'income');
			//赋值结余数
			$list[$key]['balance'] = $list[$key]['expenses'] - $num;


			
			$list[$key]['username'] = '未知';
			$ls_user = $this->UserModel->get_user($val['user_id']);
			if($ls_user){
				$list[$key]['username'] = $ls_user['nickname'];
			}
			
		}
		$res['list'] = $list;
		
		$res['total_huai'] = $total_huai;
		$res['total_yu'] = $total_yu;
		$res['total'] = $total;
		$res['date_month'] = $filter['date_month'];
		$res['date_month_txt'] = date('Y年m月',strtotime($filter['date_month'].'-01'));
		
		$res['balance_status'] = 0;
			
		$is_exist = $this->CashBalanceModel->_where_exist(array('date_month'=>$filter['date_month'],'status'=>0));
		if($is_exist){
			$res['balance_status'] = 1;
		}
		
		
		$this->data_out($res);
	}
	
	function get_huan_list(){
		
		if(!$this->check_priv('chuna_jiezhi|chuna_jiezhi_1')){
			$this->err_out(LANG_NOPRIV);
		}

		$id = $this->input->post('id',null,0);
		$info = $this->CurModel->_id_get_info($id);
		if(!$info){
			$this->err_out('数据不存在');
		}
		
		//$list = $this->CurModel->get_huai_list($info['certificate']);
		$list = $this->CurModel->get_huai_list($id);
		$this->load->model('User/UserModel','UserModel');
		foreach($list as $key=>$val){
			$list[$key]['username'] = '未知';
			$ls_user = $this->UserModel->get_user($val['user_id']);
			if($ls_user){
				$list[$key]['username'] = $ls_user['nickname'];
			}
		}
		
		
		
		
		$this->data_out($list);
	}
	function add_huan(){
		
		if(!$this->check_priv('chuna_jiezhi_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$user_id = $this->user_id;
		
		$id = $this->input->post('id',null,0);
		$post = $this->input->post();
		
		
		$info = $this->CurModel->_id_get_info($id);
		if(!$info){
			$this->err_out('数据不存在');
		}
		if($info['mtype']!=1){
			$this->err_out('当前账目不需还款');
		}
		
		$farr = array('date_month','date','info','bz','money','user_id');
		$arr = array();
		foreach($post as $key=>$val){
			if(in_array($key,$farr)){
				$arr[$key] = $val;
			}
		}
		$data = array(
			'date_month'=>'请选择月份',
			'date'=>'请选择日期',
			'bz'=>'请选择币种',
			'money'=>'请输入金额',
			'user_id'=>'请选择员工',
		);
		
		$result = $this->CheckData($data,$arr);
		if($result!==false){
			$this->err_out($result);
		}
		
		
		
		if(empty($arr['money'])){
			$this->err_out('还款数额不能为0元');
		}
		
		//获取已经还的款数
		$total = $this->CurModel->get_huai_total($id);
		//还欠的款数
		$qian_total = $info['expenses']-$total;
		if($total+$arr['money']>$info['expenses']){
			$this->err_out('还款数额超出，只需还款'.$qian_total.'元');
		}
		
		//$arr['balance'] = $info['expenses']-($total+$arr['money']);
		

		$farr = array('company','region','bumen','bumen_scale','subject','certificate','type','expenses');
		foreach($info as $key=>$val){
			if(in_array($key,$farr)){
				$arr[$key] = $val;
			}
		}
		
		
		$arr['type'] = 0;
		$time = time();
		$arr['addtime'] = $time;
		
		$income = '';
		
		$this->load->model('User/CurrencyModel','CurrencyModel');
		$curr = $this->CurrencyModel->bz_get_info($arr['bz']);
		$bs = $curr?$curr['exchange_rate']:1;
		
		$income = $arr['money'] * $bs;
		$arr['income'] = $income;

		$balance = $this->get_balance($arr['date_month']);
		$balance += $income;
		$arr['balance'] = $balance;

		//在这里更改凭证编号就行了
		$needarr = array(
			'date_month' => $this->input->post('date_month'),
			'type' => 0,
			'region' => $this->input->post('region')
		);
		$arr['certificate'] = $this->get_certificate($needarr);
		if(!$arr['certificate']){
			$this->err_out('生成凭证号码错误，参数缺失');
		}
		//添加pid
		$arr['pid'] = $id;

		$res = $this->CurModel->add($arr);
		if($res){
			if($qian_total == $income){
				$this->CurModel->edit(array('status'=>1),"id ='{$id}'");
			}
		}
		
		$this->add_log("添加还款记账信息【{$result['id']}】",'role');
		
		$this->data_out(1);
	}

	function get_balance($date_month,$id=''){
		
		$prev = $this->CashBalanceModel->get_prev_balance($date_month);
		if($prev){
			$prev_money = $prev['money'];
		}
		else{
			$prev_money = 0;
		}

		$arr = $id?array('date_month'=>$date_month,'currentID'=>$id):array('date_month'=>$date_month);

		$income = $this->CurModel->get_totals($arr,'income');
		$expenses = $this->CurModel->get_totals($arr,'expenses');
		
		$money = $prev_money + $income - $expenses;
		
		return $money;
	}
	
	//start
	/**
	* @name 导出数据
	* @return 成功返回1
	*/
	//end
	function export_data(){
		
		if(!$this->check_priv('chuna_jiezhi|chuna_jiezhi_1')){
			$this->err_out(LANG_NOPRIV);
		}
		
		
		$user_id = $this->user_id;
		


		
		$filter = $this->input->post('f',null,array());
		
		if(empty($filter['date_month'])){
			$this->err_out('请选择月份');
		}
		else{
			$filter['date_month'] = date('Y-m',strtotime($filter['date_month'].'-01'));
		}
		
		$filter['subject'] = '1031借支';
		$filter['is_export'] = 1;

		$arr = $filter;
		$res = array();
		
		$list = $this->CurModel->get_all($arr);
		
		
		$ls_arr = $filter;
		$ls_arr['mtype'] = 1;
		$total = $this->CurModel->get_totals($ls_arr,'expenses');
		
		$ls_arr = $filter;
		$ls_arr['mtype'] = 0;
		$total_huai = $this->CurModel->get_totals($ls_arr,'income');
		
		$total_yu = $total - $total_huai;
		
		$this->load->model('User/UserModel','UserModel');
		
		foreach($list as $key=>$val){
			$list[$key]['month'] = date('m',strtotime($val['date']));
			$list[$key]['day'] = date('d',strtotime($val['date']));
			
			$list[$key]['huai_date'] = !empty($val['addtime'])?date('Y-m-d',$val['addtime']):'';
			

			
			
			$list[$key]['username'] = '未知';
			$ls_user = $this->UserModel->get_user($val['user_id']);
			if($ls_user){
				$list[$key]['username'] = $ls_user['nickname'];
			}
			
		}
		$res['list'] = $list;
		
		$res['total_huai'] = $total_huai;
		$res['total_yu'] = $total_yu;
		$res['total'] = $total;
		$res['date_month'] = $filter['date_month'];
		$res['date_month_txt'] = date('Y年m月',strtotime($filter['date_month'].'-01'));
		
		$res['balance_status'] = 0;
			
		$is_exist = $this->CashBalanceModel->_where_exist(array('date_month'=>$filter['date_month'],'status'=>0));
		if($is_exist){
			$res['balance_status'] = 1;
		}
		$colunms = array(
			'month'=>'月',
			'day'=>'日',
			'region'=>'地区',
			'bumen'=>'承担部门',
			'income'=>'还款',
			'huai_date'=>'还款日期',
			'expenses'=>'支出（借出）',
			'balance'=>'结余',
			'info'=>'摘要',
			'certificate'=>'凭证编号',
			'username'=>'记账人',
		); 
		
		
		$arr = array();
		$line = 1;
		$arr['A'.$line] = "共借支：¥{$res['total']}  已还借支：¥{$res['total_huai']}  结余借支：¥{$res['total_yu']}";
		$line++;
		
		$ls_index = 0;
		foreach($colunms as $key=>$val){
			$ls_col = $this->get_char($ls_index,'A');
			$arr[$ls_col.$line] = $val;
			$ls_index++;
		}
		$line++;
		foreach($list as $key=>$val){
			$ls_index = 0;
			foreach($colunms as $k=>$v){
				$ls_col = $this->get_char($ls_index,'A');
				$arr[$ls_col.$line] = $val[$k];
				$ls_index++;
			}
			
			$line++;
		}
		
		
		
		$result = $this->Excel_write($arr);
		if(!$result){
			$this->err_out('生成Excel文件失败');
		}
		
		$url = base_url($result);
		
		$this->data_out($url);
		
	}
	
	function get_char($num,$pos='A'){
		if($num==0){
			return $pos;
		}

		for($i=0;$i<$num;$i++){
			$pos++;
		}
		return $pos;
	}
	
	function Excel_write($data,$merges=array()){
		$this->load->library('PHPExcel');
		
		// 创建Excel文件对象
		$objPHPExcel = new PHPExcel();
		// 设置文档信息，这个文档信息windows系统可以右键文件属性查看
		$objPHPExcel->getProperties()->setCreator("作者lalala")
			->setLastModifiedBy("最后更改者")
			->setTitle("文档标题")
			->setSubject("文档主题")
			->setDescription("文档的描述信息")
			->setKeywords("设置文档关键词")
			->setCategory("设置文档的分类");
		
		$objPHPExcel->setActiveSheetIndex(0);

		
									
		
		$objPHPExcel->getActiveSheet()->getStyle('A3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('B3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		
		foreach($data as $key=>$val){
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($key,$val);
		}
		
		foreach($merges as $key=>$val){
			$objPHPExcel->setActiveSheetIndex(0)->mergeCells($val);
		}
		
		$objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel ->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(0))->setAutoSize(true); 
		//$objPHPExcel->getActiveSheet()->setTitle('第一个sheet');

		// 设置第一个sheet为工作的sheet
		

		// 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$time = time();
		$dir  =  'upload/res/upload/other/'.date('Ymd');
		if(!is_dir(FCPATH . $dir)){
			@mkdir(FCPATH . $dir);
		}
		
		$file_name = $time.'_'.rand(10000,99999).'.xlsx';
		$objWriter->save(FCPATH . $dir .'/' .$file_name);
		
		return $dir .'/' .$file_name;
	}

	//获取凭证
	function get_certificate($info){
		
		if(!isset($info['region']) || !isset($info['type']) || !isset($info['date_month'])){
			return false;
		}
		$txt = '';
		$this->load->dmodel('regions','regions');
		$region = $this->regions->getRow("name='{$info['region']}'");
		
		if($region){
			$txt .= $region['sx_name'];
		}
		if(!in_array($info['type'],array(0,1))){
			$info['type'] = 2;
		}
		
		$arr = array('C','B','O');
		$txt .= $arr[$info['type']];
		
		$txt .= str_replace('-','',$info['date_month']);
		$num = $this->CurModel->getCount("date_month='{$info['date_month']}'")+1;
		
		$txt .= str_pad($num,4,"0",STR_PAD_LEFT);
		
		return $txt;
	}

	//start
	/**
	* @name 获取需要导入的列表
	* @param page ture char 页面
	* @param size ture char 数量
	* @return 成功返回1
	*/
	//end
	function get_import_list(){
		$user_id = $this->user_id;
		
		
		if(!$this->check_priv('chuna_cash|chuna_cash_1|chuna_bank|chuna_bank_1')){
			$this->err_out(LANG_NOPRIV);
		}


		$page = $this->input->post('page',null,1);
		$size = $this->input->post('size',null,10);
		
		$filter = $this->input->post('f',null,array());

		$id = $this->input->post('id',null,0);


		
		if(empty($filter['date'])){
			$this->err_out('请选择导入时间范围');
		}
		else{
			//$filter['date_month'] = date('Y-m',strtotime($filter['date_month'].'-01'));
			$filter['min_date'] = $filter['date'][0];
			$filter['max_date'] = $filter['date'][1];
		}

		//$filter['subject'] = '1031借支';
		

		// $info = array();
		
		// $info['balance_status'] = 0;
			
		// $is_exist = $this->CashBalanceModel->_where_exist(array('date_month'=>$filter['date_month'],'status'=>0));
		// if($is_exist){
		// 	$info['balance_status'] = 1;
		// }
		
		
		// $total_before = 0;
		
		
		// $prev = $this->CashBalanceModel->get_prev_balance($filter['date_month']);
		// if($prev){
		// 	$total_before = $prev['money'];
		// }
		// else{
		// 	$total_before = 0;
		// }
		
		
		$arr = $filter;
		//加入能看的主体公司权限
		$arr['company_ids'] = $this->querys;
		//当前ID
		$arr['id'] = $id;
		$arr['mtype'] = 0;//只能导入收入的数据为还款记录
		
		
		//$total_income = $this->CurModel->get_totals($arr,'income');
		//$total_expenses = $this->CurModel->get_totals($arr,'expenses');
		
		$cash_res = $this->CurModel->get_import_list($arr,$page,$size);
		
		$cash_list = $cash_res['list'];
		$info['count'] = $cash_res['count'];
		
		
		//$this->load->model('User/UserModel','UserModel');
		$this->load->model('User/SubjectModel','SubjectModel');//为了取出科目码, ling添加
		
		foreach($cash_list as $key=>$val){
			$cash_list[$key]['month'] = date('m',strtotime($val['date']));
			$cash_list[$key]['day'] = date('d',strtotime($val['date']));
			

			

			
			if($val['mtype']==0){
				$cash_list[$key]['income_s'] = $val['money'];
				$cash_list[$key]['expenses_s'] = '-';
			}
			else{
				$cash_list[$key]['income_s'] = '-';
				$cash_list[$key]['expenses_s'] = $val['money'];
			}
			
			// $cash_list[$key]['username'] = '未知';
			// $ls_user = $this->UserModel->get_user($val['user_id']);
			// if($ls_user){
			// 	$cash_list[$key]['username'] = $ls_user['nickname'];
			// }

			//通过科目名称取科目码,ling添加
			$subject_name = $this->SubjectModel->get_subject($val['subject']);
			if($subject_name){
				$cash_list[$key]['subject'] = $subject_name['code'].$cash_list[$key]['subject'];
				//$cash_list[$key]['subject_code'] = $subject_name['code'];
			}
			
		}
		$info['list'] = $cash_list;
		
		// $total = $total_before + $total_income - $total_expenses;
		// $info['total_before'] = $total_before;//上月结余
		// $info['total_income'] = $total_income;
		// $info['total_expenses'] = $total_expenses;
		// $info['total'] = $total;
		// $info['date_month'] = $filter['date_month'];
		// $info['date_month_txt'] = date('Y年m月',strtotime($filter['date_month'].'-01'));
		
		$this->data_out($info);
	}

	//导入记账
	function import_data(){

		if(!$this->check_priv('chuna_jiezhi_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$pid = $this->input->post('pid');
		$ids = $this->input->post('ids');

		if(!$pid){
			$this->err_out('参数错误');
		}

		if(count($ids)<=0){
			$this->err_out('请选择还款数据');
		}

		//当前借支信息
		$info = $this->CurModel->_id_get_info($pid);
		//获取已经还的款数
		$total = $this->CurModel->get_huai_total($pid);
		//还欠的款数
		$qian_total = $info['expenses']-$total;
		//获取所选数据的收入总数
		$huan_total = $this->CurModel->get_sum_byId($ids);
		if($total+$huan_total>$info['expenses']){
			$this->err_out('还款数额超出，只需还款'.$qian_total.'元,请重新选择！');
		}

		$res = $this->CurModel->import_data($pid,$ids);
		if($res){
			if($qian_total == $huan_total){
				$this->CurModel->edit(array('status'=>1),"id ='{$pid}'");
			}
			$this->data_out(1);
		}else{
			$this->err_out("导入失败，请稍后再试！");
		}

	}
}
